import {
  Request
} from "../../utils/request";
import host from "../../utils/host";
import func from "../../utils/functions";
// import map from "../../utils/qqmap-wx-jssdk";
const HostUrl = host.service;
const Requ = new Request();
const Func = new func();
// const Map = new map({
//   key: 'KE4BZ-POLWP-XAHDB-LCLHX-IML6V-E6B7R',
// });
var app = getApp();
var shopCar = new Array({data:[], optionalnum:0, type:1, addprice:'0.00'});  // 购物车
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navH: 0, //页面高度
    choose_send: '1', //配送方式状态
    ShopList: [], //商品列表
    total: '0.00', //合计价格
    orderid: '', //订单id
    order_choose: 'false', //订单选中状态
    data: [], //提交订单数组
    arr: [], //计算合计价格数组
    exampleList: //用户填充数组
    {
      num: 0,
      addprice: 0
    }
  },

  //返回上一级
  goback: function (event) {
    wx.navigateBack({
      delta: 1,
    });
  },
  //配送方式切换
  ChooseSend: function (e) {
    this.setData({
      choose_send: e.currentTarget.dataset.id
    })
  },
  // 预览图片
  PreImage: function (e) {
    Func.PreImage(e.currentTarget.dataset.image, e.currentTarget.dataset.image);
  },
  /**
   * 购物商品删除
   * @param {*} event 要删除的商品id
   */
  CarDelete: function(event){
    wx.request({
      url: HostUrl.SZXURL + HostUrl.CarDelete,
      method: 'POST',
      data: {
        id: event,   // 要删除的商品id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (res) => {
       if(res.data.code == 1){
        return;
       }
      }
    })
  },
  //商品数量 减
  subnum: function (event) {
    let index = event.currentTarget.dataset.index; // 商品序号
    this.data.ShopList['data'][index].num--;
    if(this.data.ShopList['data'][index].num <= 0){
      Requ.showToast('Nope');
      // 删除购物车商品id
      this.CarDelete(this.data.ShopList['data'][index].id);
      //获取购物车列表
      this.GetShopCarList();
      return;
    }
    let PromiseId = new Promise((resolve, reject)=>{
      //调用接口 编辑购物车
     wx.request({
       url: HostUrl.SZXURL + HostUrl.UpCart,
       method: 'POST',
       data: {
         id: this.data.ShopList['data'][index].id, // 商品id
         num: this.data.ShopList['data'][index].num, // 数量
       },
       header: {
         'content-type': 'application/x-www-form-urlencoded',
         'openid': app.globalData.openid,
       },
       success: (res) => {
         resolve(res);
       },
       fail: (res)=>{
         reject(res);
       }
     })
   });
   PromiseId.then((res)=>{
      //获取购物车列表
      this.GetShopCarList();
    },
    (res)=>{
      console.log(res)
      Requ.showToast('加购失败');
    });
    return;


    let id = event.currentTarget.dataset.id
    let num = event.currentTarget.dataset.num
    var shopnum = "ShopList[" + id + "].num"
    var sum = 0
    //商品数量最少为1
    if (num == 1) {} else {
      this.setData({
        [shopnum]: --num
      })
      //调用接口 编辑购物车
      wx.request({
        url: 'http://api.zyfuns.com/user/Cart/up',
        method: 'POST',
        data: {
          id: id,
          num: num
        },
        header: {
          'openid': app.globalData.openid,
        },
        success: (res) => {
          console.log(res)
        }
      })
    }
    //判断选中状态，计算价格
    this.data.arr.forEach(item => {
      sum += item.num * item.addprice
    });
    this.setData({
      total: sum.toFixed(2)
    })
  },
  // 商品数量 加
  addnum: function (event) {
    let index = event.currentTarget.dataset.index;  // 购物车列表序号
    // let num = event.currentTarget.dataset.num
    // var shopnum = "ShopList[" + index + "].num"
    // var sum = 0
    //商品数量最大为99
    if (1 == 99) {} else {
      this.data.ShopList['data'][index].num++;
      this.setData({
        // [shopnum]: ++num
        ShopList: this.data.ShopList
      });
      let PromiseId = new Promise((resolve, reject)=>{
         //调用接口 编辑购物车
        wx.request({
          url: HostUrl.SZXURL + HostUrl.AddCart,
          method: 'POST',
          data: {
            id: this.data.ShopList['data'][index].id,   // 商品id
            num: this.data.ShopList['data'][index].num, // 商品数量
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'openid': app.globalData.openid,
          },
          success: (res) => {
            resolve(res);
          },
          fail: (res)=>{
            reject(res);
          }
        })
      });
      PromiseId.then((res)=>{
        //获取购物车列表
        this.GetShopCarList();
      },
      (res)=>{
        console.log(res)
        Requ.showToast('加购失败');
      });
    }
    //判断选中状态，计算价格
    // this.data.arr.forEach(item => {
    //   sum += item.num * item.addprice
    // });
    // this.setData({
    //   total: sum.toFixed(2)
    // })
  },

  //选中状态
  Choose_list: function (event) {
    var id = event.currentTarget.dataset.id
    var sum = 0
    //选中状态 choosestu 加入 ShopList
    var choosestu = "ShopList[" + id + "].choosestu"
    this.setData({
      Listindex: id
    })
    //判断 切换选中状态 并计算价格
    if (this.data.ShopList[id].choosestu != 'true') {
      this.setData({
        [choosestu]: 'true'
      })
      //加入新数组 方便计算价格
      this.data.arr.splice(id, 1, this.data.ShopList[id])
      this.data.arr.forEach(item => {
        sum += item.num * item.addprice
      });
      this.setData({
        total: sum.toFixed(2)
      })
    } else if (this.data.ShopList[id].choosestu != 'false') {
      this.setData({
        [choosestu]: 'false'
      })
      //移出数组
      this.data.arr.splice(id, 1, this.data.exampleList)
      this.data.arr.forEach(item => {
        sum += item.num * item.addprice
      });
      this.setData({
        total: sum.toFixed(2)
      })
    }
  },

  //提交订单
  toPay: function () {
    console.log(this.data.ShopList);
    for(let key in this.data.ShopList['data']){
      shopCar[0]['data'].push(this.data.ShopList['data'][key]);
    };
    console.log(shopCar[0]);
    //调用接口
    new Request('create_order.cls.php').request(
      () => {
        return {
          goods: JSON.stringify(shopCar),
          shopid: this.MS_id,
          openid: app.globalData.openid,
        }
      },
      (res) => {
        setTimeout(function () {
          wx.navigateTo({
            url: '/pages/pay/pay?orderid=' + res.data.orderid
          })
        }, 2000)
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.MS_id = options.MS_id;
    //顶部导航高度
    this.setData({
      navH: app.globalData.navHeight,
    });
    //获取购物车列表
    this.GetShopCarList();
    
  },
  //获取购物车列表
  GetShopCarList: function(){
    wx.request({
      url: HostUrl.SZXURL + HostUrl.CartList,
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'openid': app.globalData.openid,
      },
      success: (res) => {
		  console.log(res)
        let respone = res.data;
        if(respone.data.data == 0){
          Requ.showToast('购物车列表为空', 'none', ()=>{
            setTimeout(function () {
              wx.navigateBack({
                delta: 1,
              });
          }, 2000);
          });
          return;
        }
        for(let key in respone['data']['data']){
          respone['data']['data'][key]['image'] = HostUrl.HostName + respone['data']['data'][key]['image'];
        };
        // res.data.data.data.map((e)=>{
        //   e.image = HostUrl.HostName + e.image;
        // });
        this.setData({
          ShopList: respone['data'],
        })
      }
    })
  },
})